#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/11 11:00
# @Author  : CoderCharm
# @File    : role.py
# @Software: PyCharm
# @Desc    :
"""
角色表crud操作
"""
"""
角色表项目 也就是封装
"""
from pydantic import conint
from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy import func


from api.common.curd_base import CRUDBase
from api.models.auth import AdminRole,Role,Role_resources,Resource,Company,Users,Station,Position,RespurceMutex
from ..schemas import role_schema


class CRUDRole(CRUDBase[AdminRole, role_schema.RoleCreate, role_schema.RoleUpdate]):

    @staticmethod
    def query_role(db: Session, *, role_id: int) -> Optional[AdminRole]:
        """
        此role_id是否存在
        :param db:
        :param role_id:
        :return:
        """
        return db.query(AdminRole).filter(AdminRole.role_id == role_id).first()
    # 封装role表进行创建
    def create(self, db: Session, *, obj_in: role_schema.RoleCreate) -> Role:
        db_obj = Role(
            name=obj_in.name,
            pid=obj_in.pid,
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    # 创建资源表
    def create_zi(self, db: Session, *, obj_in: role_schema.Role_Resource) -> Resource:
        db_obj = Resource(
            # name 菜单名称
            name=obj_in.name,
            # 排序
            pid=obj_in.pid,
            # 路径
            url=obj_in.url,
            restype=obj_in.restype
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj





    # 获取二级分类的分页数据
    @staticmethod
    def queryall_resource(db:Session)->dict:
        res=db.query(Resource).filter(Resource.pid!=0).all()
        result=[{"key":i.id,"label":i.name,"pid":i.pid} for i in res]
        return {
            "items":result,
        }

    # 根据id查询角色的数据
    @staticmethod
    def get_roleresource(db: Session, *, roleid:int) -> dict:
       res=db.query(Role_resources).filter(Role_resources.rid==roleid).all()
       reslist=[]
       print('*******',res)
       if res:
           reslist=[i.eid for i in res]
       return {
            "items": reslist
       }
    @staticmethod
    def setResource(db: Session, *, roleid:int,idlist:str) -> bool:
        # 删除此角色对应的资源
       db.query(Role_resources).filter(Role_resources.rid==roleid).delete()
       # db.commit()
       print("************",idlist)
       idl=idlist.split(',')
       # for i in idl:
       #     db_obj=Role_resources(
               # id=0,
               # rid=roleid,
               # eid=i
           # )
           # db.add(db_obj)
       # 查询此角色是否有继承角色，如果有查询继承角色所对应的资源
       roles=db.query(Role).filter(Role.id==roleid).first()
       print(str(roles.pid))
       if roles.pid>0:
            pidresource= db.query(Role_resources).filter(Role_resources.rid==roles.pid).all()
            for i in pidresource:
                resid=str(i.eid)
                if resid not in idl:
                    idl.append(i.eid)

            print(idl)
       # for i in idl:
       #      # 根据i查询互斥表
       #      # sql="select * from resoource_mutex where resourceid1=%d or resourceid2=%d"%(int(i),int(i))
       #      # res=db.execute(sql)
       #      reslist=[]
       #      for rid in res:
       #          reslist.append(str(rid.resourceid1))
       #          reslist.append(str(rid.resourceid2))
       #      interlist=list(set(idl).intersection(set(reslist)))
       #      if len(interlist)>1:
       #          return False
       #      db_obj=Role_resources(
       #              id=0,
       #              rid=roleid,
       #              eid=i
       #      )
       #      db.add(db_obj)
       # db.commit()
       return True






    @staticmethod
    def setPrpResource(db: Session, *, roleid: int, idlist: str) -> bool:

        idl = idlist.split(',')
        # 定义一个权限值为0
        promition=0
        for i in idl:
            resource=db.query(Role_resources).filter(Role_resources.id==i).first()
            promition=promition | resource.promition

        # 查询此角色是否有继承角色，如果有查询继承角色所对应的资源
        roles = db.query(Role).filter(Role.id == roleid).first()
        if roles.pid > 0:
            # 查询父类的权限列表和promition权限 |
            resource = db.query(Role).filter(Role.id == roleid).first()
            promition=promition | resource.promition
        sql="update role set promition=%d where id=%d"%(promition,roleid)
        db.execute(sql)
        db.commit()
        return True

    # 获取资源表
    @staticmethod
    def query_restype(db: Session, *, page: int = 1, page_size: int) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Resource.id)).filter(Resource.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Resource).filter(Resource.is_delete == 0).offset(
            temp_page).limit(page_size).all()

        items = [{"name": obj.name,
                  "pid": obj.pid,"url":obj.url,"restype":obj.restype} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }

    # 查询角色的数据
    @staticmethod
    def query_all(db: Session, *, page: int = 1, page_size: conint(le=50) = 10) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Role.id)).filter(Role.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Role).filter(Role.is_delete == 0).offset(
            temp_page).limit(page_size).all()

        items = [{"id":obj.id,"name": obj.name,
                  "pid": obj.pid} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }


    # 创建用户表
    def create_user(self, db: Session, *, obj_in: role_schema.Users_table) -> Users:
        db_obj = Users(
            # name 菜单名称
            account=obj_in.account,
            password=obj_in.password,
            name=obj_in.name,
            number=obj_in.number,
            sex=obj_in.sex,
            phone=obj_in.phone,
            company_id=obj_in.company_id,
            depart_id=obj_in.depart_id,
            pid=obj_in.pid,
            jid=obj_in.jid,
            rid=obj_in.rid,
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
curd_role = CRUDRole(AdminRole)



# 公司
class CCompany(CRUDBase[Company, role_schema.company_table, role_schema.RoleUpdate]):
    # 创建公司表
    def create_mange(self, db: Session, *, obj_in: role_schema.company_table) -> Company:
        db_obj = Company(
            name=obj_in.name,
            coding=obj_in.coding,
            type=obj_in.type,
            sort=obj_in.sort,
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    # 获取公司
    @staticmethod
    def query_mage(db: Session, *, page: int = 1, page_size: int) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Resource.id)).filter(Resource.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Company).filter(Resource.is_delete == 0).offset(
            temp_page).limit(page_size).all()

        items = [{"coding": obj.coding,"type": obj.type, "name": obj.name, "sort": obj.sort} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }
comm=CCompany(Company)


# 用户
class UUser(CRUDBase[Users, role_schema.Users_table, role_schema.RoleUpdate]):
    # 创建用户
    def create_users(self, db: Session, *, obj_in: role_schema.Users_table) -> Users:
        db_obj = Users(
            account=obj_in.account,
            password=obj_in.password,
            name=obj_in.name,
            sex=obj_in.sex,
            number=obj_in.number,
            phone=obj_in.phone,
            company_id=obj_in.company_id,
            depart_id=obj_in.depart_id,
            pid=obj_in.pid,
            jid=obj_in.jid,
            rid=obj_in.rid,
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj



    # 获取用户
    @staticmethod
    def query_user(db: Session, *, page: int = 1, page_size: int) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Resource.id)).filter(Resource.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Users).filter(Resource.is_delete == 0).offset(temp_page).limit(page_size).all()

        items = [{"account": obj.account,"password": obj.password, "name": obj.name, "sex": obj.sex,
                  "number": obj.number,
                  "phone": obj.phone,
                  "company_id": obj.company_id,
                  "depart_id": obj.depart_id,
                  "pid": obj.pid,
                  "jid": obj.pid,
                  "rid": obj.rid,
                  } for obj in query_obj]
        return {
            "items": items,
            "total": total
        }

    # 获取侧边栏分类
    @staticmethod
    def getMenu(db:Session,*,roleid:int)->list:
        role=db.query(Role).filter(Role.id==roleid).first()
        sql=" select res.id,res.name,res.pid,res.url,pres.name as pname,res.promition from resources as res left join resources as pres on res.pid=pres.id where res.restype=2 and res.pid>0;"
        res=db.execute(sql)
        print('*****')
        list=[]
        for i in res:
            print(i.promition)
            flag=role.promition & i.promition
            a=dict(i)
            if flag>0:
                list.append(a)

        return list
    # @staticmethod
    # def workerflower(db:Session,*,wid:int,params:str)->dict:
    #     res=db.query(Workflow).filter(Workflow)

uuser=UUser(Users)


# 岗位
class SStation(CRUDBase[Station, role_schema.Station_table, role_schema.RoleUpdate]):
    # 创建岗位
    def create_station(self, db: Session, *, obj_in: role_schema.Station_table) -> Station:
        db_obj = Station(
            coding=obj_in.coding,
            sort=obj_in.sort,
            name=obj_in.name,
            desc=obj_in.desc,

        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    # 获取用户
    @staticmethod
    def query_station(db: Session, *, page: int = 1, page_size: int) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Resource.id)).filter(Resource.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Station).filter(Resource.is_delete == 0).offset(temp_page).limit(page_size).all()

        items = [{"coding": obj.coding,"sort": obj.sort, "name": obj.name, "desc": obj.desc,} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }
sstat=SStation(Station)


# 职位
class PPosition(CRUDBase[Position, role_schema.Position_table, role_schema.RoleUpdate]):
    # 创建岗位
    def create_ppos(self, db: Session, *, obj_in: role_schema.Position_table) -> Position:
        db_obj = Position(
            duty_name=obj_in.duty_name,
            sort=obj_in.sort,
            duty_num=obj_in.duty_num,
            uid=obj_in.uid,
            cid=obj_in.cid,

        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    # 获取用户
    @staticmethod
    def query_ppos(db: Session, *, page: int = 1, page_size: int) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Resource.id)).filter(Resource.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Position).filter(Resource.is_delete == 0).offset(temp_page).limit(page_size).all()

        items = [{"duty_name": obj.duty_name,"duty_num": obj.duty_num, "sort": obj.sort,"uid": obj.uid, "descripe": obj.descripe,"cid": obj.cid,} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }
ppos=PPosition(Position)
